//
//  YH_InfoPubViewController.m
//  YinHang
//
//  Created by 123 on 14-6-20.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_InfoPubViewController.h"
#import "YH_InfoSyncViewController.h"

#import "SEInputAccessoryView.h"
#import "SEStampInputView.h"
#import "SEPhotoView.h"
#import "SETextView.h"

static const CGFloat defaultFontSize = 15.0f;
#define origin_y 55

@interface YH_InfoPubViewController ()<SETextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    CGRect keyboardBounds;
    
    UIImage *input_normalImg;
    UIImage *input_onImg;
    
    UIImagePickerController *imgPC;//UIImagePickerController对象
    
    EncodeToMP4 *encodeToMP4;//视频压缩帮助类
    BOOL isVideo;
    
    UIImage *image;//最终的图片
    UIImage *thumbnail;//视频第一帧
    
    NSString *imgFileByte;//图片上传filebyte参数
    NSString *videoFileByte;//视频上传filebyte参数
    NSString *fileByte;//内容图片上传filebyte参数
    
    NSUInteger selectedIndex_;
    
    NSArray *catData;//类别data
    NSMutableArray *catArr;//省份名称数组
    
    
    MBProgressHUD *postHud;
    
    BOOL isContentInput;
    
    
    /* 文件上传（内容图片）*/
    ASIFormDataRequest *contentImgUploadRequest;
    /* 文件上传（图片/视频）*/
    ASIFormDataRequest *fileuploadRequest;
    /* 提交发布信息请求 */
    ASIFormDataRequest *postInfoRequest;
    
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    NSString *filename;
    NSString *tid_;
    
    NSMutableArray *fileByteArr;
    NSArray* reversedArray;
    
    NSString *content;//返回图片地址后和内容拼成的字符串
    NSString *imgFilePath;//图片或视频缩略图地址
    NSString *videoFilePath;//视频地址
    NSString *filePath;//内容图片地址
}
// SERichTextEditor
@property (weak, nonatomic) IBOutlet UILabel *contentLbl;

@property (weak, nonatomic) IBOutlet UIImageView *textViewBgImgView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//@property (weak, nonatomic) IBOutlet SETextView *textView;
@property (weak, nonatomic) IBOutlet UITextView *textView;

@property (nonatomic) SEInputAccessoryView *inputAccessoryView;
@property (nonatomic) SEStampInputView *imageInputView;

@property (nonatomic) id normalFont;
@property (nonatomic) id boldFont;

@end

@implementation YH_InfoPubViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden=NO;
    self.navigationItem.title = @"信息发布";
    [self customBarButtonItem];
    
    //加载视图
    [self setUI];
    
    // 加载选项卡
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"新闻", @"人才", @"视频", @"产品", @"图片",@"服务"]];
    // 默认选中新闻
    selectedIndex_ = 0;
    action = @"newsadd";//添加新闻
    
    [segmentedControl setIndexChangeBlock:^(NSUInteger index) {
        selectedIndex_ = index;
        
        _contentLbl.hidden = NO;
        _textViewBgImgView.hidden = NO;
        _scrollView.hidden = NO;
        
        switch (index) {
            case 0://新闻
                action = @"newsadd";//添加新闻
                
                _chooseTypeTxtField.text = nil;
                
                if (isVideo) {
                    _imgView.image = nil;
                } else {
                    _imgView.image = image;
                    isVideo = NO;
                }
                
                break;
            case 1://人才
                action = @"zhaopinadd";//添加招聘信息
                
                _chooseTypeTxtField.text = nil;
                
                if (isVideo) {
                    _imgView.image = nil;
                } else {
                    _imgView.image = image;
                    isVideo = NO;
                }
                
                break;
            case 2://视频
                _contentLbl.hidden = YES;
                _textViewBgImgView.hidden = YES;
                _scrollView.hidden = YES;
                
                action = @"videosadd";//添加视频信息
                
                _chooseTypeTxtField.text = nil;
                
                if (!isVideo) {
                    _imgView.image = nil;
                } else {
                    _imgView.image = thumbnail;
                    isVideo = YES;
                }
                
                break;
            case 3://产品
                action = @"prosadd";//添加产品信息
                
                _chooseTypeTxtField.text = nil;
                
                if (isVideo) {
                    _imgView.image = nil;
                } else {
                    _imgView.image = image;
                    isVideo = NO;
                }
                
                break;
            case 4://图片
                action = @"casesadd";//添加案例信息
                
                _chooseTypeTxtField.text = nil;
                
                if (isVideo) {
                    _imgView.image = nil;
                } else {
                    _imgView.image = image;
                    isVideo = NO;
                }
                break;
            case 5://服务
            {
                action = @"serinforadd";
                _chooseTypeTxtField.text = nil;
                
                if (isVideo) {
                    _imgView.image = nil;
                } else {
                    _imgView.image = image;
                    isVideo = NO;
                }

            }break;
                
            default:
                break;
        }
    }];
    [segmentedControl setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 35)];
    [self.view addSubview:segmentedControl];
    
    // 初始化SERichTextEditor
    [self SERichTextEditorInit];
    
    isVideo = NO;
    isContentInput = NO;
}

- (void)customBarButtonItem {
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 35)];
    UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    [rightBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    [rightBtn setTitle:@"提交" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(post) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    if (ios7) {
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,rightBarButtonItem];
    }else{
        self.navigationItem.rightBarButtonItems = @[rightBarButtonItem];
    }
}

- (void)setUI {
    input_normalImg = [UIImage imageNamed:@"input_normal"];
    input_onImg = [UIImage imageNamed:@"input_on"];
    
    
    // 设置背景
    [_chooseTypeTxtField setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_titleTxtField setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    // 设置文本颜色
    _chooseTypeTxtField.textColor = TEXT_COLOR;
    _titleTxtField.textColor = TEXT_COLOR;
    // 设置文本偏移
    [_chooseTypeTxtField setPadding:YES top:0 right:15 bottom:0 left:15];
    [_titleTxtField setPadding:YES top:0 right:15 bottom:0 left:15];
    
    _textViewBgImgView.image = [input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f];
    
    
    UIImage *img = [UIImage imageNamed:@"infopub_img_bg"];
    _bgImgView.image = [img stretchableImageWithLeftCapWidth:img.size.width*0.5f topCapHeight:img.size.height*0.5f];
    
    UIImage *photoBtn_bgImg = [UIImage imageNamed:@"infopub_filesuploadbtn"];
    [_choosePhotoBtn setBackgroundImage:[photoBtn_bgImg stretchableImageWithLeftCapWidth:photoBtn_bgImg.size.width*0.5f topCapHeight:photoBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    [_takePhotoBtn setBackgroundImage:[photoBtn_bgImg stretchableImageWithLeftCapWidth:photoBtn_bgImg.size.width*0.5f topCapHeight:photoBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    _choosePhotoBtn.tintColor = TEXT_COLOR;
    _takePhotoBtn.tintColor = TEXT_COLOR;
}

// 初始化SERichTextEditor
- (void)SERichTextEditorInit {
    self.imageInputView = [[[UINib nibWithNibName:@"SEStampInputView" bundle:nil] instantiateWithOwner:nil options:nil] lastObject];
    NSArray *btnArr = @[self.imageInputView.button1,self.imageInputView.button2,self.imageInputView.button3,self.imageInputView.button4,self.imageInputView.button5,self.imageInputView.button6,self.imageInputView.button7,self.imageInputView.button8,self.imageInputView.button9,self.imageInputView.button10,self.imageInputView.button11,self.imageInputView.button12,self.imageInputView.button13,self.imageInputView.button14,self.imageInputView.button15];
    for (UIButton *btn in btnArr) {
        [btn addTarget:self action:@selector(stamp:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.inputAccessoryView = [[[UINib nibWithNibName:@"SEInputAccessoryView" bundle:nil] instantiateWithOwner:nil options:nil] lastObject];
    self.inputAccessoryView.keyboardButton.target = self;
    self.inputAccessoryView.keyboardButton.action = @selector(showKeyboard:);
    self.inputAccessoryView.stampButton.target = self;
    self.inputAccessoryView.stampButton.action = @selector(showStampInputView:);
    self.inputAccessoryView.photoButton.target = self;
    self.inputAccessoryView.photoButton.action = @selector(showImagePicker:);
    self.inputAccessoryView.nomalButton.target = self;
    self.inputAccessoryView.nomalButton.action = @selector(nomal:);
    self.inputAccessoryView.boldButton.target = self;
    self.inputAccessoryView.boldButton.action = @selector(bold:);
    
    //self.textView.inputAccessoryView = self.inputAccessoryView;
    self.textView.editable = YES;
    //self.textView.lineSpacing = 8.0f;
    
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@""];
    
    NSFont *normalFont = [NSFont systemFontOfSize:defaultFontSize];
    CTFontRef ctNormalFont = CTFontCreateWithName((__bridge CFStringRef)normalFont.fontName, normalFont.pointSize, NULL);
    self.normalFont = (__bridge id)ctNormalFont;
    CFRelease(ctNormalFont);
    
    NSFont *boldFont = [NSFont boldSystemFontOfSize:defaultFontSize];
    CTFontRef ctBoldFont = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
    self.boldFont = (__bridge id)ctBoldFont;
    CFRelease(ctBoldFont);
    
    self.textView.font = [UIFont systemFontOfSize:defaultFontSize];
    
    self.textView.attributedText = attributedString;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 选择类别
- (IBAction)chooseCategory:(id)sender {
    
    // 进入类别请求界面
    GetCatTableViewController *getCatVC = [[GetCatTableViewController alloc]init];
    getCatVC.delegate = self;
    
    getCatVC.selectedTag = selectedIndex_;
    
    UINavigationController *getCatNav = [[UINavigationController alloc]initWithRootViewController:getCatVC];
    getCatNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:22.0]};
    
    if (MAIN_VERSION >= 7) {
        getCatNav.navigationBar.barTintColor = APP_COLOR;
        
    } else {
        getCatNav.navigationBar.tintColor = APP_COLOR;
    }
    
    [self presentViewController:getCatNav animated:YES completion:nil];
}

#pragma mark - ShowCatDelegate

- (void)showCat:(NSString *)cat Tid:(NSString *)tid SelectedIndex:(NSInteger)selectedRow {
    
    tid_ = tid;
    _chooseTypeTxtField.text = cat;
}


#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    isContentInput = NO;
    
    [textField setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
    
    //self.inputAccessoryView.keyboardButton.enabled = NO;
    //self.inputAccessoryView.photoButton.enabled = NO;
    //self.inputAccessoryView.stampButton.enabled = NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [textField setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    
    //self.inputAccessoryView.keyboardButton.enabled = NO;
    //self.inputAccessoryView.photoButton.enabled = YES;
    //self.inputAccessoryView.stampButton.enabled = YES;
    
    isContentInput = YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    return YES;
}

#pragma mark - touchMethod
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [super touchesBegan:touches withEvent:event];
    
    [self allEditActionsResignFirstResponder];
    
    [postHud hide:YES];
    
    [contentImgUploadRequest cancel];
    [fileuploadRequest cancel];
    [postInfoRequest cancel];
}

#pragma mark - PrivateMethod
- (void)allEditActionsResignFirstResponder{
    [_titleTxtField resignFirstResponder];
    [_textView resignFirstResponder];
}


// 选择文件
- (IBAction)choosePhotoFromPhotoAlbum:(id)sender {
    isContentInput = NO;
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        imgPC = [[UIImagePickerController alloc]init];
        imgPC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 媒体类型——相册
        //imgPC.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        if (selectedIndex_ != 2) {//不是视频
            // 设置媒体类型(NSArray)（指定是选择静态的图片还是录像）
            imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
        } else {// 视频
            imgPC.mediaTypes = @[(NSString*)kUTTypeMovie];
        }
        //imgPC.allowsEditing = YES;
        imgPC.delegate = self;
        
        [self presentViewController:imgPC animated:YES completion:nil];
    }
}

// 拍照上传
- (IBAction)takePhoto:(id)sender {
    // 检查设备是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        // 创建UIImagePickerController对象
        imgPC = [[UIImagePickerController alloc]init];
        // 设置源类型（确定是调用摄像头还是调用图片库）
        imgPC.sourceType = UIImagePickerControllerSourceTypeCamera;
        if (selectedIndex_ != 2) {//不是视频
            // 设置媒体类型(NSArray)（指定是拍静态的图片还是录像）
            imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
        } else {// 视频
            imgPC.mediaTypes = @[(NSString*)kUTTypeMovie];
        }
        
        // 设置允许编辑
        imgPC.allowsEditing = YES;
        // 设置代理对象
        imgPC.delegate = self;
        
        // 弹出模式视图控制器
        [self presentViewController:imgPC animated:YES completion:nil];
    }
}


#pragma mark - SERichTextEditor

- (void)viewWillLayoutSubviews
{
    [self updateLayout];
}

#pragma mark -

- (void)textViewDidBeginEditing:(SETextView *)textView
{
    self.textView.selectedRange = NSMakeRange(self.textView.text.length,0);
    
    _textViewBgImgView.image = [input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f];
}

- (void)textViewDidEndEditing:(SETextView *)textView
{
    [self.textView resignFirstResponder];
    _textViewBgImgView.image = [input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f];
}

- (void)textViewDidChangeSelection:(SETextView *)textView
{
    NSRange selectedRange = textView.selectedRange;
    //NSRange selectedRange = NSMakeRange(self.textView.text.length,0);
    if (selectedRange.location != NSNotFound && selectedRange.length > 0) {
        self.inputAccessoryView.boldButton.enabled = YES;
        self.inputAccessoryView.nomalButton.enabled = YES;
    } else {
        self.inputAccessoryView.boldButton.enabled = NO;
        self.inputAccessoryView.nomalButton.enabled = NO;
    }
}

- (void)textViewDidChange:(SETextView *)textView
{
    [self updateLayout];
}

#pragma mark -

- (void)keyboardWillShow:(NSNotification *)notification
{
    [notification.userInfo[UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
    
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    if (isContentInput) {
        // 改变视图位置
        if (IPHONE5) {
            CGFloat heightCha = (self.scrollView.frame.origin.y-(self.view.bounds.size.height-(CGRectGetHeight(keyboardBounds)+CGRectGetHeight(self.inputAccessoryView.bounds))-CGRectGetHeight(self.scrollView.bounds)));
            self.myView.frame = CGRectMake(self.myView.frame.origin.x,origin_y-heightCha-20, self.myView.bounds.size.width, self.myView.bounds.size.height);
        } else {
            CGFloat heightCha = (self.scrollView.frame.origin.y-(self.view.bounds.size.height-(CGRectGetHeight(keyboardBounds)+CGRectGetHeight(self.inputAccessoryView.bounds))-CGRectGetHeight(self.scrollView.bounds)));
            self.myView.frame = CGRectMake(self.myView.frame.origin.x,origin_y-heightCha+30, self.myView.bounds.size.width, self.myView.bounds.size.height);
        }
    }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [notification.userInfo[UIKeyboardFrameEndUserInfoKey] getValue:&keyboardBounds];
    
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // 回归视图原位置
    self.myView.frame = CGRectMake(self.myView.frame.origin.x, origin_y, self.myView.bounds.size.width, self.myView.bounds.size.height);
}

- (void)updateLayout
{
    CGSize containerSize = self.scrollView.frame.size;
    CGSize contentSize = [self.textView sizeThatFits:containerSize];
    
    CGRect frame = self.textView.frame;
    frame.size.height = MAX(contentSize.height, containerSize.height);

    self.textView.frame = frame;
    self.scrollView.contentSize = frame.size;
    
    //[self.scrollView scrollRectToVisible:self.textView.caretRect animated:YES];
}

#pragma mark -

- (IBAction)showKeyboard:(id)sender
{
    self.textView.inputView = nil;
    [self.textView reloadInputViews];
    
    self.inputAccessoryView.keyboardButton.enabled = NO;
    self.inputAccessoryView.stampButton.enabled = YES;
}

- (IBAction)showStampInputView:(id)sender
{
//    self.textView.inputView = self.imageInputView;
//    [self.textView reloadInputViews];
//    
//    self.inputAccessoryView.keyboardButton.enabled = YES;
//    self.inputAccessoryView.stampButton.enabled = NO;
}

- (IBAction)showImagePicker:(id)sender
{
    //[self.textView resignFirstResponder];
    
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    controller.delegate = self;
    controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:controller animated:YES completion:NULL];
}

- (IBAction)nomal:(id)sender
{
    NSRange selectedRange = self.textView.selectedRange;
    if (selectedRange.location != NSNotFound && selectedRange.length > 0) {
        self.textView.font = nil;
        
        NSMutableAttributedString *attributedString = self.textView.attributedText.mutableCopy;
        [attributedString addAttribute:(id)kCTFontAttributeName value:self.normalFont range:selectedRange];
        self.textView.attributedText = attributedString;
    }
}

- (IBAction)bold:(id)sender
{
    NSRange selectedRange = self.textView.selectedRange;
    if (selectedRange.location != NSNotFound && selectedRange.length > 0) {
        self.textView.font = nil;
        
        NSMutableAttributedString *attributedString = self.textView.attributedText.mutableCopy;
        [attributedString addAttribute:(id)kCTFontAttributeName value:self.boldFont range:selectedRange];
        self.textView.attributedText = attributedString;
    }
}

- (IBAction)stamp:(id)sender
{
    UIButton *button = sender;
    UIImage *stampImage = [button imageForState:UIControlStateNormal];
    
    //[self.textView insertObject:stampImage size:stampImage.size];
}


#pragma mark - UIImagePickerControllerDelegate

// 拍摄完成后要执行的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//    
//    if (isContentInput) {//是内容里的图片
//        UIImage *image_ = info[UIImagePickerControllerOriginalImage];
//        
//        SEPhotoView *photoView = [[SEPhotoView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 80.0f)];
//        photoView.image = image_;
//        
//        //[self.textView insertObject:photoView size:photoView.bounds.size];
//        
//        [self dismissViewControllerAnimated:YES completion:^{
//            //  插入图片后 光标重新定位
//            self.textView.selectedRange = NSMakeRange(self.textView.text.length,0);
//        }];
//        
//    } else {
//        isContentInput = YES;
    
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        
        // 处理照片
        if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
            
            UIImage *origImg;//原始图片
            UIImage *editedImg;//编辑后的图片
            
            
            // 获取原始图片
            origImg = [info objectForKey:UIImagePickerControllerOriginalImage];
            // 获取编辑后的图片
            editedImg = [info objectForKey:UIImagePickerControllerEditedImage];
            
            if (editedImg) {
                image = editedImg;
            }else{
                image = origImg;
            }
            
            if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
                // 保存到相机胶卷（相册图库）
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
            }
            
            _imgView.image = image;
            
            
            // 视频缩略图data
            NSData *imageData = UIImagePNGRepresentation(image);
            imgFileByte = [imageData hexadecimalString];
            //NSLog(@"%@",imgFileByte);
            
            isVideo = NO;
            
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        // 处理录像
        if ([mediaType isEqualToString:(NSString*)kUTTypeMovie]) {
            // 视频路径
            NSURL *videoUrl_Origin = [info objectForKey:UIImagePickerControllerMediaURL];
            NSString *videoPath = (NSString*)[videoUrl_Origin path];
            //NSLog(@"%@",videoPath);
            
            if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
                
                if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath)) {
                    
                    UISaveVideoAtPathToSavedPhotosAlbum(videoPath, nil, nil, nil)
                    ;
                }
            }
            
            //NSLog(@"%@",videoUrl_Origin);
            
            // 显示视频缩略图
            MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoUrl_Origin];
            moviePlayer.shouldAutoplay = NO;
            thumbnail = [moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
            
            _imgView.image = thumbnail;
            // 图片data
            NSData *imageData = UIImagePNGRepresentation(thumbnail);
            imgFileByte = [imageData hexadecimalString];
            //NSLog(@"%@",imgFileByte);
            
            isVideo = NO;
            
            // 初始化视频压缩帮助类
            encodeToMP4 = [[EncodeToMP4 alloc]init];
            encodeToMP4.delegate = self;
            // 开始压缩
            [encodeToMP4 start:videoUrl_Origin hasVideo:YES isSave:NO];
            
            
            [self dismissViewControllerAnimated:YES completion:^{
//                // 播放视频
//                MPMoviePlayerViewController *pvc = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]];
//                [self presentMoviePlayerViewControllerAnimated:pvc];
//                [pvc.moviePlayer play];
            }];
        }
    
}

#pragma mark - SendResultUrl
// 压缩完成后传回来的视频地址
- (void)backResultDatainfo:(NSURL *)url {
    //NSLog(@"%@",url);
    NSData *videoData = [NSData dataWithContentsOfURL:url];
    
    videoFileByte = [videoData hexadecimalString];
    //NSLog(@"%@",videoFileByte);
    
    isVideo = YES;
}

// 点击cancel后执行的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 获取当前时间
- (NSString*)getCurrentDateTime {
    NSDate *senddate=[NSDate date];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMddhhmmss"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    //NSLog(@"locationString:%@",locationString);
    
    return locationString;
}

/* 文件上传（内容图片）*/
- (void)postContentImg {
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        // 提示正在加载数据...
        postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        postHud.labelText = @"正在发布，请稍后...";
        
        
        contentImgUploadRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        contentImgUploadRequest.requestMethod = @"POST";
        // 设置超时时间
        contentImgUploadRequest.timeOutSeconds = 60;
        contentImgUploadRequest.delegate = self;
        // 设置参数
        
        // 拼接内容中图片转为16进制后的str ,分隔
        
        //NSLog(@"%@",self.textView.attachments);//无序的
        //NSLog(@"%@",self.textView.attachmentsArr);//有序的
        //reversedArray = [[self.textView.attachmentsArr reverseObjectEnumerator] allObjects];
        
        fileByteArr = [NSMutableArray array];
        
        
        for (SETextAttachment *attachment in reversedArray) {
            SEPhotoView *photoView = attachment.object;
            UIImage *contentImg = photoView.image;
            
            // 内容图片data
            NSData *imgData = UIImagePNGRepresentation(contentImg);
            NSString *byteStr = [imgData hexadecimalString];
            
            [fileByteArr addObject:byteStr];
        }

        
        // 图片名（多张的话也需要,拼接）
        filename = [self getCurrentDateTime];
        NSMutableArray *filenameArr = [NSMutableArray array];
        // 如果只有一个  就不用拼接了
        if (fileByteArr.count == 1) {
            filename = [NSString stringWithFormat:@"%@_0.png",filename];
            fileByte = fileByteArr[0];
        } else {
            for (int i=0; i<fileByteArr.count; i++) {
                NSString *filenameStr = [NSString stringWithFormat:@"%@_%d.png",filename,i];
                [filenameArr addObject:filenameStr];
            }
            
            // ,号拼接
            filename = [filenameArr componentsJoinedByString:@","];
            fileByte = [fileByteArr componentsJoinedByString:@","];
        }
        paramsDict = @{@"cid":UID,@"uid":UNAME,@"filename":filename,@"filebyte":fileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"fileupload",paramsStr];
        NSData *paramsData = [result toGBKEncodingData];
        contentImgUploadRequest.postBody = [paramsData mutableCopy];
        
        [contentImgUploadRequest startAsynchronous];
    }
}

/* 文件上传（图片/视频缩略图 || 视频）*/
- (void)fileUpload {
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        fileuploadRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        fileuploadRequest.requestMethod = @"POST";
        // 设置超时时间
        fileuploadRequest.timeOutSeconds = 60;
        fileuploadRequest.delegate = self;
        // 设置参数
        filename = [self getCurrentDateTime];
        NSString *actionStr = @"";
        if (!isVideo) {
            actionStr = @"fileupload1";
            filename = [NSString stringWithFormat:@"%@.png",filename];
            paramsDict = @{@"uid":UNAME,@"cid":UID,@"filename":filename,@"filebyte":imgFileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        } else {
            actionStr = @"fileuploadvideo";
            filename = [NSString stringWithFormat:@"%@.flv",filename];
            paramsDict = @{@"uid":UNAME,@"cid":UID,@"filename":filename,@"filebyte":videoFileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        fileuploadRequest.postBody = [paramsData mutableCopy];
        
        [fileuploadRequest startAsynchronous];
    }
}

/* 提交发布信息请求 */
- (void)postInformation {
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postInfoRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postInfoRequest.requestMethod = @"POST";
        // 设置超时时间
        postInfoRequest.timeOutSeconds = 60;
        postInfoRequest.delegate = self;
        // 设置参数
        if (selectedIndex_ == 1 && !_imgView.image) {//人才中图片是可选项（人才且没图片）
            paramsDict = @{@"cid":UID,@"uid":UNAME,@"title":_titleTxtField.text,@"content":content,@"tid":tid_};//uid会员名;title标题;content内容;tid分类
        } else if (selectedIndex_ == 2) {//视频 content传视频路径 picture传视频缩略图地址
            paramsDict = @{@"cid":UID,@"uid":UNAME,@"title":_titleTxtField.text,@"content":videoFilePath,@"tid":tid_,@"picture":imgFilePath};
        } else {
            paramsDict = @{@"cid":UID,@"uid":UNAME,@"title":_titleTxtField.text,@"content":content,@"tid":tid_,@"picture":imgFilePath};//uid会员名;title标题;content内容;tid分类;picture图片地址
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        paramsStr = [paramsStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postInfoRequest.postBody = [paramsData mutableCopy];
        
        [postInfoRequest startAsynchronous];
    }
}


// 提交！！
- (void)post {
    [self.textView resignFirstResponder];
    // 看必填内容是否为空
    if ([NSString emptyValidate:_chooseTypeTxtField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请选择类别！"];
        
        return;
    }
    if ([NSString emptyValidate:_titleTxtField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请填写标题！"];
        
        return;
    }
    if (selectedIndex_ != 1) {//人才中图片是可选项
        if (!_imgView.image) {
            if (selectedIndex_ == 2) {
                [SVProgressHUD showErrorWithStatus:@"请选择视频！"];
            } else {
                [SVProgressHUD showErrorWithStatus:@"请选择图片！"];
            }
            
            return;
        }
    }
    if (selectedIndex_ != 2 && [NSString emptyValidate:_textView.text]) {//视频没内容
        [SVProgressHUD showErrorWithStatus:@"请填写内容！"];
        
        return;
    }
    
    content = self.textView.text;
    
    
    // 如果内容里有图片  先上传内容中的图片
//    if (self.textView.attachmentsArr.count != 0) {
//        
//        /* 文件上传（内容图片）*/
//        [self postContentImg];
//        
//    } else
    if (_imgView.image) {// 如果内容里没图片 上传图片或视频缩略图
        
        isVideo = NO;
        
        /* 文件上传（图片/视频缩略图）*/
        [self fileUpload];
        
    } else {// 内容图片和图片视频都没有（人才中图片可选） 直接发布
        
        /* 提交发布信息请求 */
        [self postInformation];
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    postHud.hidden = YES;
    NSLog(@"%@",request.responseString);
    if (request == contentImgUploadRequest) {
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                // 文件（内容图片）上传成功
                NSDictionary *info = result[@"info"];
                filePath = info[@"filepath"];//图片地址(以,分割的)
                
                // 多张图片
                //NSMutableArray *imgPathArr = [NSMutableArray array];
//                if (self.textView.attachmentsArr.count > 1) {
//                    NSArray *pathArr = [filePath componentsSeparatedByString:@","];
//                    
//                    for (NSString *path in pathArr) {
//                        NSString *imgPath = [NSString stringWithFormat:@"%@",path];
//                        [imgPathArr addObject:imgPath];
//                    }
//                    
//                    
//                    // 图片地址替换占位符#
//                    
//                    for (int i=0; i<self.textView.attachmentsArr.count; i++) {
//                        NSRange range = [content rangeOfString:CONTENTIMAGE_REPLACEMENT_CHARACTER];
//                        //content = [content stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"<img src=\"%@\"/>",imgPathArr[i]]];
//                        content = [content stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%@",imgPathArr[i]]];
//                    }
                
//                } else {
//                    // 图片地址替换占位符(#)
//                    content = [content stringByReplacingOccurrencesOfString:CONTENTIMAGE_REPLACEMENT_CHARACTER withString:[NSString stringWithFormat:@"%@",filePath]];
//                    //NSLog(@"%@",content);
//                }
                
                if (selectedIndex_ == 1 && !_imgView.image) {
                    /* 提交发布信息请求 */
                    [self postInformation];
                } else {
                    /* 文件上传（图片/视频）*/
                    [self fileUpload];
                }
            } else {
                [postHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    } else if (request == fileuploadRequest) {
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                
                // 文件（图片、视频）上传成功
                NSDictionary *info = result[@"info"];
                if (!isVideo) {
                    imgFilePath = info[@"filepath"];//图片地址
                    //imgFilePath = [NSString stringWithFormat:@"%@%@",URL_DOMAIN,info[@"filepath"]];//图片地址
                    if (selectedIndex_ == 2) {
                        isVideo = YES;
                    }
                    
                } else {
                    videoFilePath = info[@"filepath"];//视频地址
                    
                    isVideo = NO;
                }
                
                if (isVideo) {
                    /* 文件上传（图片/视频）*/
                    [self fileUpload];
                } else {
                    /* 提交发布信息请求 */
                    [self postInformation];
                }
                
            } else {
                [postHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    } else {
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [postHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                NSString *newsId = info[@"id"];
                
                
                // 提示发布成功
                [UIView animateWithDuration:0 animations:^{
                    
                    [SVProgressHUD showSuccessWithStatus:@"发布成功！"];
                    
                } completion:^(BOOL finished) {
                    
                    // 进入信息同步页...
                    YH_InfoSyncViewController *infoSyncVC = [[YH_InfoSyncViewController alloc]initWithNibName:@"YH_InfoSyncViewController" bundle:nil];
                    infoSyncVC.newsId = newsId;
                    infoSyncVC.mid = [NSString stringWithFormat:@"%lu", (unsigned long)selectedIndex_+1];
                    
                    [self.navigationController pushViewController:infoSyncVC animated:YES];
                }];
            } else {
                [postHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [postHud hide:YES];
    postHud = nil;
    //BOOL b = postHud.hidden;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


// 返回
- (void)back {
    [contentImgUploadRequest cancel];
    [fileuploadRequest cancel];
    [postInfoRequest cancel];
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
